# Clean up
rm(list = ls())
Sys.setenv(LANG = "en")

# Set working directory: please set your own
#setwd("~/Dropbox/sanctions_replication/")

# Load necessary packages
library(tidyverse)
library(readstata13)

# Import dataset
data <- read.dta13("data/survey_clean.dta")

# Make the plot
figureb2 <- data %>%
  drop_na(pbeliefs_psoe_num, 
          pmoral_psoe_num,
          pharm_psoe_num,
          normexpect_psoe_num,
          smoral_psoe_num,
          sharm_psoe_num,
  ) %>%
  select("pbeliefs_psoe_num", "pmoral_psoe_num", "pharm_psoe_num",
         "normexpect_psoe_num", "smoral_psoe_num", "sharm_psoe_num")  %>%
  mutate(socially_self_psoe = ifelse(pbeliefs_psoe_num < 4, "No", "Yes")) %>%
  mutate(morally_self_psoe = ifelse(pmoral_psoe_num < 4, "No", "Yes")) %>%
  mutate(harmful_self_psoe = ifelse(pharm_psoe_num < 3, "Yes", "No")) %>%
  mutate(socially_others_psoe = ifelse(normexpect_psoe_num < 4, "No", "Yes")) %>%
  mutate(morally_others_psoe = ifelse(smoral_psoe_num < 4, "No", "Yes")) %>%
  mutate(harmful_others_psoe = ifelse(sharm_psoe_num < 3, "Yes", "No")) %>%
  
  select("socially_self_psoe", "morally_self_psoe", "harmful_self_psoe",
         "socially_others_psoe", "morally_others_psoe", "harmful_others_psoe")  %>%
  
  `colnames<-`(c("Socially Appropriate (Self)", "Morally Appropriate (Self)", "Harmful (Self)", 
                 "Socially Appropriate (Others)", "Morally Appropriate (Others)", "Harmful (Others)")) %>%
  # make into long format
  pivot_longer(cols = c(`Socially Appropriate (Self)`:`Harmful (Others)`),
               names_to = "Group") %>%
  
  mutate(Variable = ifelse(Group %in% c("Socially Appropriate (Self)", "Socially Appropriate (Others)"), "Socially Appropriate",
                           ifelse(Group %in% c("Morally Appropriate (Self)", "Morally Appropriate (Others)"), "Morally Appropriate", 
                                  "Harmful"))) %>%  
  
  mutate(Order = ifelse(Group %in% c("Socially Appropriate (Self)", "Morally Appropriate (Self)", "Harmful (Self)"), "First-order (self)",
                        "Second-order (others)"))  %>%
  
  group_by(Variable) %>%
  mutate(overall_n = n()) %>%
  ungroup() %>%
  group_by(Group, value) %>%
  mutate(group_n = n(), na.rm = T) %>%
  mutate(prop = group_n / overall_n, na.rm = T) %>%
  mutate(percent = prop * 100, na.rm = T)  %>%
  ggplot(aes(x = value, y = percent, group = Order, color = Order, na.rm = TRUE)) + 
  geom_bar(aes(y = ..prop.., linetype = value), position = position_dodge(width = 1), fill = "white", na.rm = TRUE) +
  geom_text(aes(y = ..prop.., label = scales::percent(..prop..)),
            stat = 'count', position = position_dodge(width = 1), vjust = -0.5) +
  theme_bw() +
  labs(x = "Survey response", y = "Share of respondents") +
  scale_color_manual(values = c("red", "blue")) +
  scale_fill_manual(values = c("red", "blue")) +
  facet_wrap(~Variable)
figureb2

ggsave("figures/figureb2.png", plot = figureb2, width = 25, height = 12.5, units = "cm")